import React,{Component} from 'react';

// 面向对象 扩展方法

export default class LifeCycle extends Component{
    // 很多生命周期函数
    constructor(){
        super(); // 父类方法
        this.state={  // 自有状态
            number:0, 
            users:[]
        }
        console.log('1. constructor 初始化 props and state');
    }
    // 组件模板渲染前不要发送数据请求
    // 用户体验 快

    componentWillMount(){    // 即将挂载
        console.log('2. compontWillMount 组件将要挂载');
    }

    componentDidMount(){
        console.log('4. componentDidMount 组件挂载完成');
        // render 执行完了
        fetch('https://api.github.com/users')
        .then(res=>res.json())
        .then(users=>{
            console.log(users);
            this.setState({users});
        })
    }

    //性能优化
    shouldComponentUpdate(nextProps,nextState){
        console.log('5. shouldComponentUpdate 询问组件是否需要更新？');
        if(nextState.number==this.state.number){
            return false;
        }
        return 5;
    }

    componentWillUpdate(){
        console.log('6. coponentWillUpdate 组件即将更新');
    }

    componentDidUpdate(){
        console.log('7. componentDidupdate 组件更新完毕');
    }

    render(){
        console.log('3. render 渲染，挂载');
        return (
            <div style={{border:'5px solid red',padding:'5px'}}>
                <p>{this.props.name}:{this.state.number}</p>
                <button onClick={this.add.bind(this)}>+</button>
                {this.state.number%2==0 && <SubCounter number={this.state.number} />}
                <ul>
                    {
                        this.state.users.map(user=><li key={user.id}>{user.login}</li>)
                    }
                </ul>
            </div>)
    }
    add(){
        this.setState({
            number:this.state.number+1
        })
        
    }
}


// 可拔插的组件
class SubCounter extends Component{
    constructor(props){
        super(props);
        this.state={count:0}
    }
    // 子组件 收到数据
    componentWillReceiveProps(){
        console.log('SubCounter 1.componentWillReceiveProps');
    }
    componentWillUnmount(){
        console.log('subcounter 3. componentWillUnmount');
    }
    shouldComponentUpdate(nextProps,nextState){
        console.log('subCountershouldupdate',nextState,nextProps);
        if(nextProps.number % 3 ==0){
            return true;
        }
        else{
            return false;
        }
    }
    render(){
        console.log('subcounter 2.render');
        return(
            <>
            subcounter{this.props.number}
            </>
        )
    }
}